//
//  CarcircleAddViewController.m
//  CarUser
//
//  Created by 王森林 on 2019/1/19.
//  Copyright © 2019年 王森林. All rights reserved.
//

#import "CarcircleAddViewController.h"
#import "YQBPlaceTextView.h"
#import  "CustomImagePickUtility.h"
#import "UserRes.h"
@interface CarcircleAddViewController ()<UITextViewDelegate>
@property (nonatomic, strong) UIView *topicTypeView;
@property (nonatomic, strong) UIView *topicTitleView;
@property (nonatomic, strong) UIView *topicContentView;
@property (nonatomic, strong) UIView *topicImgsView;
@property (nonatomic, strong) UITextField *titleField;
@property (nonatomic, strong) YQBPlaceTextView *contentTextView;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic) float width;
@property (nonatomic, strong) NSMutableArray *imgAry;

@property  (nonatomic, strong)  NSArray  *btnAry;
@property (nonatomic) NSInteger currentIndex;
@property (nonatomic) NSInteger preIndex;
@property (nonatomic, strong) UILabel *wenziLabel;
@property (nonatomic, strong) UILabel *tupianLabel;
@end
#define BTNTAG 100
#define DELBTN 1000
#define IMGAEBTN 10000
@implementation CarcircleAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"发帖";
    [self setNaviDefaultRightBtnWithTitle:@"完成" andSel:@selector(handleCompleteAction)];
    self.width = (BOUNDWIDTH-30-40)/5;
    [self createUI];
    // Do any additional setup after loading the view.
}

- (void)createUI
{
    [self.view addSubview:self.topicTypeView];
    self.topicTypeView.frame = CGRectMake(0, 0, BOUNDWIDTH, 100);
    [self createTypeView];
    [self updateBtnStatus:0];
    
    [self.view addSubview:self.topicTitleView];
    self.topicTitleView.frame = CGRectMake(0, 110, BOUNDWIDTH, 40);
    [self createTitleView];
    
    [self.view addSubview:self.topicContentView];
    self.topicContentView.frame = CGRectMake(0, 160, BOUNDWIDTH, 100);
    [self createContentView];
    
    [self.view addSubview:self.topicImgsView];
    self.topicImgsView.frame = CGRectMake(0, 270, BOUNDWIDTH, 150);
    [self createImgsView];
    
}

- (void)updateImgsView
{
    
    self.tupianLabel.text = [NSString stringWithFormat:@"%lu/5",self.imgAry.count];
    
    [self.topicImgsView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[UIImageView class]]) {
            [obj removeFromSuperview];
        }
    }];
    if (self.imgAry.count == 0) {
        self.addBtn.frame = CGRectMake(15+(self.width+10)*self.imgAry.count, 30, self.width, self.width);
        return;
    }
    
    
    
    [self.imgAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        [btn setBackgroundImage:obj forState:UIControlStateNormal];
        //        btn.frame = CGRectMake(15+(self.width+10)*idx, 0, self.width, self.width);
        //        [self.imgsView addSubview:btn];
        UIImageView *imageView = [UIImageView new];
        imageView.image = obj;
        imageView.userInteractionEnabled = YES;
        imageView.tag  = IMGAEBTN + idx;
        imageView.frame = CGRectMake(15+(self.width+10)*idx, 30, self.width, self.width);
        [self.topicImgsView addSubview:imageView];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:@"suggest_del"] forState:UIControlStateNormal];
        btn.frame = CGRectMake(self.width-20, -20, 40, 40);
        btn.tag  = DELBTN + idx;
        [btn addTarget:self action:@selector(handleDelAction:) forControlEvents:UIControlEventTouchUpInside];
        [imageView addSubview:btn];
        
        
    }];
    if (self.imgAry.count<5) {
        self.addBtn.frame = CGRectMake(15+(self.width+10)*self.imgAry.count, 30, self.width, self.width);
    }
    
}

- (void)handleDelAction:(id)sender
{
    UIButton  *btn = sender;
    NSInteger tag = btn.tag - DELBTN;
    UIImageView  *imageView = [self.view viewWithTag:tag+IMGAEBTN];
    [self.imgAry removeObject:imageView.image];
    [self  updateImgsView];
    
}


#pragma mark -------------CustomImagePickUtilityDelegate
- (void)pickPhotoWithImage:(NSArray *)imgsAry{
    
    if (imgsAry.count ==0) {
        return;
    }
    
    [self.imgAry addObjectsFromArray:imgsAry];
    [self updateImgsView];
    
    //
    //    UIImage *uploadImage  =  imgsAry[0];
    //    NSData *data = UIImageJPEGRepresentation(uploadImage, 0.3);
    //    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}


-(void)uploadImgs:(NSString *)suggestId
{
    
    
    
    if (self.imgAry.count == 0) {
        return;
    }
    [self.imgAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        
        
//        UserRes *user = [CommonMethod getUser];
        
        UIImage *uploadImage  =  self.imgAry[0];
        NSData *oridata = UIImageJPEGRepresentation(uploadImage, 1);
        NSData *data =  nil;
        NSLog(@"dsds大小%ld",[oridata length]/1024/1024);
        if (([oridata length]/1024/1024)> 1) {
            data = UIImageJPEGRepresentation(uploadImage, 0.3);
        } else {
            data = oridata;
        }
        
       
//        NSLog(@"大小%d",[data length]);
        NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        
        
        NSDictionary *params = @{
                                 @"FKEY":[CommonMethod createMD5Key:@"NULL"],
//                                 @"TOKEN":user.TOKEN,
//                                 @"USERNAME":user.mobile,
                                 @"TALK_ID":suggestId,
                                 @"IMGSTR":encodedImageStr,
                                 @"HZM000":@"jpg"
                                 };
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showWithStatus:nil];
        });
        
        [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_38 params:params md5Paraname:@"" success:^(id  _Nullable response) {
            
            
            if ((self.imgAry.count-1) == idx) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [SVProgressHUD showInfoWithStatus:@"发帖成功"];
                    //                [SVProgressHUD dismissWithDelay:10];
                });
                [self.navigationController popViewControllerAnimated:YES];
            }
            
            
            
        } fail:^(NSError * _Nonnull error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showErrorWithStatus:error.localizedDescription];
            });
        }];
        
    }];
    
}



- (void)handleCompleteAction
{
    if ([CommonMethod isBlankString:self.titleField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请输入标题"];
        return ;
    }
    if ([CommonMethod isBlankString:self.contentTextView.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"请输入内容"];
        
        return ;
    }
//    if (self.imgAry.count == 0) {
//
//        [SVProgressHUD showErrorWithStatus:@""];
//
//        return ;
//    }
    
    UserRes *user = [CommonMethod getUser];
    if (!user) {
        [[NSNotificationCenter defaultCenter]postNotificationName:NotificationCenterName_AlertLoginVC object:nil];
        return;
    }
    NSDictionary *params = @{
                             @"FKEY":[CommonMethod createMD5Key:@"TOKEN"],
                             @"TOKEN":user.TOKEN,
                             @"type":[NSString stringWithFormat:@"%ld",self.currentIndex],
                             @"title":self.titleField.text,
                             @"content":self.contentTextView.text
                             };
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:nil];
    });
    
    [[ZY_AfnNetManager shareInstance]postWithURL:Car_API_37 params:params md5Paraname:@"" success:^(id  _Nullable response) {
        
        
        //        dispatch_async(dispatch_get_main_queue(), ^{
        //            [SVProgressHUD dismiss];
        //        });
        
        NSDictionary *result =  response;
        if (self.imgAry.count > 0 ) {
             [self uploadImgs:[result objectForKey:@"TALK_ID"]];
            
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [SVProgressHUD showInfoWithStatus:@"发帖成功"];
                //                [SVProgressHUD dismissWithDelay:10];
            });
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        

        
    } fail:^(NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];
        });
    }];
    
    
}


- (void)handleAddAction
{
        [CustomImagePickUtility showSheet:self andTitle:@"选择图片" andImageCount:5-self.imgAry.count WithEditCamera:YES];
    
}


- (void)handleBtnAction:(id)sender
{
    UIButton *btn = sender;
    [self updateBtnStatus:btn.tag-BTNTAG];
    
}

- (void)updateBtnStatus:(NSInteger)index
{
    
    UIButton  *currentBtn = (UIButton *)[self.topicTypeView viewWithTag:index+BTNTAG];
    NSString *title = self.btnAry[currentBtn.tag - BTNTAG];
    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    [result setObject:title forKey:@"title"];
    if (!currentBtn.selected) {
        [result setObject:@"1" forKey:@"operation"];
        currentBtn.selected = YES;
        currentBtn.layer.borderColor = RGB(40, 40, 40).CGColor;
    } else {
        [result setObject:@"2" forKey:@"operation"];
        currentBtn.selected = NO;
        currentBtn.layer.borderColor = Common_TextLowColor.CGColor;
    }
    
   
    
    self.preIndex = self.currentIndex;
    self.currentIndex = index;
    if (self.preIndex != -1) {
        if (self.preIndex == index) {
            return;
        }
        UIButton *preBtn = (UIButton *)[self.topicTypeView viewWithTag:self.preIndex+BTNTAG];
        preBtn.selected = NO;
        preBtn.layer.borderColor = Common_TextLowColor.CGColor;
        NSString *title = self.btnAry[self.preIndex];
        [result setObject:title forKey:@"title"];
        [result setObject:@"2" forKey:@"operation"];
     
    }
    
    
    
}

- (void)createImgsView
{

    self.addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.addBtn setBackgroundImage:[UIImage imageNamed:@"suggest_add"] forState:UIControlStateNormal];
    self.addBtn.frame = CGRectMake(15, 30, self.width, self.width);
    [self.addBtn addTarget:self action:@selector(handleAddAction) forControlEvents:UIControlEventTouchUpInside];
    [self.topicImgsView addSubview:self.addBtn];
    
    self.tupianLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, self.width + 45, 60, 15)];
    self.tupianLabel.text  = @"0/5";
    self.tupianLabel.textColor = Common_HeadTitle_Color;
    self.tupianLabel.font = FONT_SIZE(12);
    self.tupianLabel.textAlignment = NSTextAlignmentLeft;
    [self.topicImgsView addSubview:self.tupianLabel];
    
}

- (void)createContentView
{
//    self.contentTextView = [[YQBPlaceTextView alloc]init];
//    self.contentTextView.frame = CGRectMake(15, 10, BOUNDWIDTH-30, 60);
//    self.contentTextView.font = FONT_SIZE(14);
//    self.contentTextView.textColor = Common_TextColor;
//    self.contentTextView.placeholder = @"用文字记录此刻你心中所想";
//    [self.topicContentView addSubview:self.contentTextView];
    
    
    UIView *textBGView = [UIView new];
    textBGView.backgroundColor = [UIColor whiteColor];
    textBGView.frame = CGRectMake(15, 10, BOUNDWIDTH -30, 85);
    [self.topicContentView addSubview:textBGView];
    
    
    self.contentTextView = [[YQBPlaceTextView alloc]init];
    self.contentTextView.frame = CGRectMake(10, 5, BOUNDWIDTH-20, 70);
    self.contentTextView.font = FONT_SIZE(14);
    self.contentTextView.textColor = Common_TextColor;
    self.contentTextView.placeholder = @"用文字记录此刻你心中所想";
    self.contentTextView.delegate = self;
    [self.topicContentView addSubview:self.contentTextView];

    
    self.wenziLabel = [[UILabel alloc] initWithFrame:CGRectMake(BOUNDWIDTH- 95, 70, 60, 10)];
    self.wenziLabel.text  = @"0/500";
    self.wenziLabel.textColor = RGB(51, 51, 51);
    self.wenziLabel.font = FONT_SIZE(12);
    self.wenziLabel.textAlignment = NSTextAlignmentRight;
    [textBGView addSubview:self.wenziLabel];
    
}


#pragma mark - TextViewDelegate
//输入时自动删除占位文字
- (void)textViewDidBeginEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"";
    }
}

//当编辑时动态判断是否超过规定字数，这里限制20字
- (void)textViewDidChange:(UITextField *)textView{
    
    if (textView.text.length > 500) {
        textView.text = [textView.text substringToIndex:500];
    }
    //这里的_strLengthLbl为动态显示已输入字数，可按情况添加
    self.wenziLabel.text = [NSString stringWithFormat:@"%lu/500",textView.text.length];
}

//编辑结束后如内存为空自动添加占位文字
- (void)textViewDidEndEditing:(UITextView *)textView{
    if ([textView.text isEqualToString:@""]) {
        textView.text = @"占位文字";
    }
}

- (void)createTitleView
{
    
    self.titleField  = [[UITextField alloc] initWithFrame:CGRectMake(15, 5, BOUNDWIDTH - 30, 30)];
    self.titleField.placeholder = @"编辑标题";
    self.titleField.font = FONT_SIZE(14);
    [self.topicTitleView addSubview:self.titleField];
    
}

- (void)createTypeView
{
    
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 4, 15)];
    lineLabel.backgroundColor = Common_NavigroundColor;
    lineLabel.layer.cornerRadius = 2;
    lineLabel.layer.masksToBounds = YES;
    [self.topicTypeView addSubview:lineLabel];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(23, 10, BOUNDWIDTH - 50, 15)];
    titleLabel.text = @"选择话题分类";
    titleLabel.font = FONT_SIZE(15);
    titleLabel.textColor = [UIColor blackColor];
    [self.topicTypeView addSubview:titleLabel];
    self.btnAry = @[@"用车养车",@"购车交流",@"帮选车",@"车市行情 "];
    float width = (BOUNDWIDTH - 70)/4;
    [self.btnAry enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton  *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:obj forState:UIControlStateNormal];
        [btn setTitleColor:Common_TextLowColor forState:UIControlStateNormal];
        [btn setTitleColor:RGB(40, 40, 40) forState:UIControlStateSelected];
        btn.titleLabel.font = FONT_SIZE(12);
        btn.layer.cornerRadius = 5;
        btn.layer.masksToBounds = YES;
        btn.layer.borderColor =  Common_TextLowColor.CGColor;
        btn.layer.borderWidth = 1;
        btn.frame = CGRectMake(20+(10+width)*idx, 40, width, 35);
        btn.tag = BTNTAG + idx;
        [btn addTarget:self action:@selector(handleBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.topicTypeView addSubview:btn];

    }];
}

-  (UIView *)topicTypeView
{
    if (!_topicTypeView) {
        _topicTypeView = [UIView new];
        _topicTypeView.backgroundColor = [UIColor whiteColor];
    }
    return _topicTypeView;
}

-  (UIView *)topicTitleView
{
    if (!_topicTitleView) {
        _topicTitleView = [UIView new];
        _topicTitleView.backgroundColor = [UIColor whiteColor];
    }
    return _topicTitleView;
}

-  (UIView *)topicContentView
{
    if (!_topicContentView) {
        _topicContentView = [UIView new];
        _topicContentView.backgroundColor = [UIColor whiteColor];
    }
    return _topicContentView;
}

-  (UIView *)topicImgsView
{
    if (!_topicImgsView) {
        _topicImgsView = [UIView new];
        _topicImgsView.backgroundColor = [UIColor whiteColor];
    }
    return _topicImgsView;
}

-  (NSMutableArray *)imgAry
{
    if (!_imgAry) {
        _imgAry = [NSMutableArray new];
    }
    return _imgAry;
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
